// 02login/01register/register.js
var co = require('../../resource/js/common.js')
var map = require('../../resource/js/map.js')
var app = getApp()
var pKeys = ['latitude', 'longitude']
var _this, _data
var image = ''
var imageReal = ''
var _Sms_Code
//首页输入的手机， 是否已是商家     定时器
var _inputPhone, _notShop, interval = null;
//是否结束定时器
var isExitCountTime = 0,
   _opt
//省市区
var p = 0,
   c = 0,
   d = 0

Page({
   data: {
      user: 0, //用户信息
      Verified_Phone: '', //验证的手机号,初始为0，自动登录后变为非0，以确认要否显示微信授权
      getSmsCodeText: '获取验证码',
      Verified_Ok: '', //验证正确否
      isCode: 0, //验证码0错误，1正确
      src: '', // 选择的图片路径
      imgSrc: '',
      isImage: false,
      shopInfo: [], // 店铺信息
      isShop: 0,
      isLogin: 1, //1表示未授权。0表示已授权 
      detail_info: '', // 选择店铺
      // detail_place: '',
      bizID: '',
      showBizReg: 0,
      // loveBiz: false,
      orgReg: false,
      // 省市区三级联动初始化
      region: ["", "", ""],
      province: '', //选中的省    
      provinceName: [],
      provinceCode: [],
      provinceSelIndex: '',
      city: '', //选中的市
      cityName: [],
      cityCode: [],
      citySelIndex: '',
      district: '', //选中的区
      districtName: [],
      districtCode: [],
      districtSelIndex: '',
      showMessage: false, //保存地址时候是否符合规格
      messageContent: '', //保存时未满足要求提示语
      showDistpicker: false,
      name: '',
      tel: '',
      address: '',
      Address_ID: '',
      inprovince: '',
      inprovinceId: '',
      incity: '',
      incityId: '',
      indistrict: '',
      indistrictId: '',
      Address_Is_Default: '',
      addressCode: '', //地址编号
      select: [0, 0, 0],
      wd: '', //纬度
      jd: '', //经度
   },

   onLoad(opt) {
      _this = this
      _data = this.data
      console.log('商家注册opt====', opt)
      // //  请求省的数据
      // this.getProvince()
      //去自动登录
      this.toAutoLogin()
      //处理页面参数
      _opt = wx.getStorageSync('opt')
      console.log('商家注册_opt2222====', _opt)
      if (_opt.BizType == 'meal' || _opt.BizType == 'public') {

      } else {
         wx.setNavigationBarTitle({
            title: '注册',
         })
         _this.setData({
            orgReg: true
         })
      }
      this.setData({
         showBizReg: 1
      })
   },

   onUnload() {
      isExitCountTime = 1
   },

   //一键获取微信认证手机
   getPhoneNumber(e) {
      app.decryptWxInfoData(e.detail, function(res) {
         _this.setData({
            Verified_Ok: 1,
            Verified_Phone: res.phoneNumber
         })
      })
   },

   //手机输入框失去焦点
   inputPhone(e) {
      _inputPhone = e.detail.value
      console.log('【inputPhone(e)】===' + _inputPhone)
   },

   //检查手机格式
   checkPhone(phone) {
      var pho = phone ? phone : _inputPhone
      var rule = /^1[0-9]{10}$/
      console.log('【checkPhone(phone)==】' + pho)
      if (rule.test(pho)) {
         return 1
      }
      return 0
   },

   //倒计时
   countDown(time) {
      var second = ''
      setTimeout(function() {
         if (time > 0) {
            time--
            second = '(' + time + '秒)'
            _this.setData({
               getSmsCodeText: '重新获取' + second
            })
            if (!isExitCountTime) {
               _this.countDown(time)
            }
         } else {
            isExitCountTime = 0
            _this.setData({
               getSmsCodeText: '重新获取' + second
            })
         }
      }, 1000);
   },

   // 输入验证码
   inputCode(e) {
      console.log('输入码==' + e.detail.value)
      if (_Sms_Code == e.detail.value) {
         // if ('232' == e.detail.value)
         isExitCountTime = 1
         this.setData({
            Verified_Ok: 1,
            Verified_Phone: _data.Verified_Phone
         })
      }
   },

   //换个手机
   changePhone() {
      this.setData({
         Verified_Ok: 0,
         Verified_Phone: ''
      })
   },

   // 获取短信验证码
   getPhoneCode() {
      if (!this.checkPhone()) {
         co.toastAllText('手机号格式不正确3')
         return
      }
      _this.setData({
         Verified_Phone: _inputPhone
      })
      co.getShareApi('api/Sms/getPhoneCode', {
         mobile: _inputPhone,
         type: 'user_reg'
      }, function(res) {
         if (res.code == 0) {
            _Sms_Code = res.data.Sms_Code
            var second = 90
            _this.setData({
               getSmsCodeText: '重新获取(' + second + '秒)'
            })
            _this.countDown(second)
         } else {
            co.toastAllText(res.msg)
         }
      })
   },

   //点击授权
   getWxUserInfo(e) {
      var session_key = wx.getStorageSync('session_key')
      if (co.empty(session_key)) {
         app.wxLogin(function(res) {
            console.log("【app.wxLogin登录结果】===", res)
            _this.get_user_info(e.detail)
         })
         return
      }
      this.getUserInfo(e.detail)
   },

   //获取用户 或 注册 或更新
   getUserInfo(data) {
      if (co.empty(data.iv) || co.empty(data.encryptedData))
         return
      var IUID = _opt.InviterID
      co.getShareApi('user/Mg/getInfo', {
         appid: app.Data.app.appid,
         session_key: wx.getStorageSync('session_key'),
         iv: data.iv,
         encryptedData: data.encryptedData,
         User_Mobile: this.data.Verified_Phone,
         Owner_Id: IUID ? IUID : 0
      }, function(res) {
         if (res.code != 0) {
            _this.setData({
               user: ''
            })
            co.toastAllText(res.msg)
            return
         }
         app.Data.userInfo = res.data
         _this.setData({
            user: res.data
         })
      })
   },

   //选择所在位置
   selectAddress(e) {
      wx.chooseLocation({
         success(res) {
            console.log("【允许授权】===", res)
            map.getLocationName(res, function(res2) {
               //console.log('res2======',res2)
               var str = res2.location.result
               _this.setData({
                  detail_info: str.address_component.street_number,
                  wd: str.ad_info.location.lat,
                  jd: str.ad_info.location.lng,
                  inprovince: str.address_component.province,
                  incity: str.address_component.city,
                  indistrict: str.address_component.district
               })

               _this.getPuaCode()
            })

         },
         fail: function(res) {
            if (res.errMsg.indexOf('auth') != -1) {
               wx.openSetting({
                  success: function(res) {
                     wx.setStorageSync("noMap", 1)
                  }
               })
            }
         }
      })
   },

   //选择图片
   chooseImage() {
      wx.chooseImage({
         count: 1, // 最多可以选择的图片张数，默认9
         sizeType: ['compressed'],
         sourceType: ['album', 'camera'],
         success(res) {
            if (res.tempFilePaths.length > 0) {
               _this.setData({
                  src: res.tempFilePaths[0],
                  isImage: true
               })
               //上传图片
               _this.uploadImage(res.tempFilePaths[0])
            }
         },
      })
   },

   //上传图片
   uploadImage(filePath) {
      //图片上传返回路径
      wx.uploadFile({
         url: 'https://api.w293.cn/api/Upload/img',
         filePath: filePath,
         name: 'image',
         formData: {
            dir: 'shopLogo/Biz'
         },
         success: function(res) {
            console.log("【返回图片信息】===", res)
            var obj = JSON.parse(res.data)
            if (obj.code == 0) {
               console.log('obj'.obj)
               var img = obj.data
               image = img.wwwPath
               imageReal = img.relativePath
            } else {
               co.toastAllText(obj.msg)
            }
         }
      })
   },

   //删除照片
   deleteImage(e) {
      co.getJyhsApi('upload/File/deleteImg', {
         imageFile: imageReal
      }, function(res) {
         if (res.code == 0) {
            _this.setData({
               src: '',
               isImage: false
            })
            image = ''
            imageReal = ''
         }
      })
   },

   //提交信息
   submitBizInfo(e) {
      var info = e.detail.value
      var IUID = _opt.InviterID
      var bizType = _opt.BizType
      var telRule = /^1[0-9]{10}$/         
      if (info.Biz_Account == '') {
         console.log(1)
         _this.showMessage('请输入商家名称')
      } 
      // else if (info.Biz_Name == '') {
      //    _this.showMessage('请输入证件全称')
      // }
       else if (info.Biz_Phone == '') {
         _this.showMessage('请输入手机号码')
      } else if (!telRule.test(info.Biz_Phone)) {
         _this.showMessage('手机号码格式不正确5')
      } else if (info.Biz_Contact == '') {
         _this.showMessage('请输入姓名')
      } else if (info.Address_Province == '') {
         _this.showMessage('请选择所在省')
      } else if (info.Address_City == '') {
         _this.showMessage('请选择所在市')
      } else if (info.Address_Area == '' && this.info.districtCode.length != 0) {
         _this.showMessage('请选择所在地区')
      } else if (info.Address_Detailed == '') {
         _this.showMessage('请输入详细地址')
      } else {
         var param = {
            Biz_Account: info.Biz_Account,
            Biz_Contact: info.Biz_Contact,
            Biz_Phone: info.Biz_Phone,
            Biz_Name: info.Biz_Name,
            Biz_PrimaryLng: _data.jd, //经度
            Biz_PrimaryLat: _data.wd, //纬度
            Shop_Photo: image,
            User_ID: app.Data.userInfo.User_ID,
            unionid: app.Data.userInfo.unionid,
            Biz_Detail_Address: info.Address_Detailed,
            Biz_Province:_data.addressCode.PID,
            Biz_City: _data.addressCode.CID,
            Biz_Area: _data.addressCode.AID,
         }
         console.log('param===', param)
         co.getShareApi('jyhs/Admin/regBiz', param, function(res) {
            console.log("【获取注册返回信息】res=====", res)
            if (res.code == 0) {
               console.log(res.data)
               _this.setData({
                  bizID: res.data.biz_list[0].Biz_ID
               })
               app.Data.userInfo = res.data.userInfo
               _this.showMessage(' 升级成功')
               setTimeout(function () {
                  var pages = getCurrentPages(),
                     prevPage = pages[pages.length - 2];
                  prevPage.setData({
                     alter: "123"
                  })
                  wx.navigateBack({})
               }, 2000)
            } else {
               co.Modal(res.msg)
            }
         })

      }


   },

   //选择店铺进入
   selectShop(e) {
      var id = e.currentTarget.id
      co.confirm('', '进入' + _data.shopInfo[id].Biz_Account, '取消', '确认', function(res) {
         if (res) {
            wx.setStorageSync('shopInfo', _data.shopInfo[id])
            app.Data.shopInfo = _data.shopInfo[id]
            app.switchTabHome()
         }
      })
   },

   //提示手机认证
   showToast() {
      co.toastAllText('请先手机认证')
   },

   //准备自动登录
   toAutoLogin() {
      var session = wx.getStorageSync('session')
      console.log('session', session)
      if (!co.empty(session.unionid) || !co.empty(session.openid)) {
         this.autoLogin(session)
         return
      }

      app.wxLogin(function(res) {
         _this.autoLogin(res)
      })
   },

   //自动登录
   autoLogin(obj) {
      co.getShareApi("user/Mg/autoLogin", {
         unionid: obj.unionid,
         openid: obj.openid, //因为换appid，需要更新Wx_Openid
         appid: app.Data.app.appid //因为换appid，需要更新Wx_Openid
      }, function(res) {
         if (res.code == 29300) {
            _this.doUserData([], '', '')
            return;
         }
         var d = res.data
         var biz_list = co.empty(d.biz_list) ? [] : d.biz_list
         _this.doUserData(biz_list, d.userInfo, d.userInfo.User_Mobile)
      })
   },

   //处理自动登录的用户数据
   doUserData(biz_list, userInfo, mobile) {
      app.Data.userInfo = userInfo
      if (biz_list.length)
         app.Data.shopInfo = biz_list[0]
      this.setData({
         user: userInfo,
         shopInfo: biz_list,
         Verified_Ok: _this.checkPhone(mobile),
         Verified_Phone: mobile
      })
      console.log('_data====', _data)
   },
 
   //显示提示信息
   showMessage: function(text) {
      //console.log(2)
      _this.setData({
         showMessage: true,
         messageContent: text
      })
      
      setTimeout(function() {
         //console.log(3)
         _this.setData({
            showMessage: true,
            messageContent: text
         })
         setTimeout(function() {
            //console.log(4)
            _this.setData({
               showMessage: false,
               messageContent: ''
            })
         }, 3000)
      })
   },
   //获取省市区编号
   getPuaCode: function() {
      var url = 'api/Areas/getPCACode'
      var param = {
         Province_Name: _data.inprovince,
         City_Name: _data.incity,
         Area_Name: _data.indistrict
      }
      co.getShareApi(url, param, function(res) {
         if (res.code == 0) {
            _this.setData({
               addressCode: res.data
            })
         }
      })
   },

})